package com.douziit.meilianoa.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.douziit.meilianoa.base.enums.ButtenEnum;
import com.douziit.meilianoa.base.request.PageRequest;
import com.douziit.meilianoa.base.response.ResponseUtil;
import com.douziit.meilianoa.dto.ButtenInfo;
import com.douziit.meilianoa.dto.ProjectListInfo;
import com.douziit.meilianoa.entity.*;
import com.douziit.meilianoa.mapper.ProjectInfoMapper;
import com.douziit.meilianoa.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 项目信息操作服务   实现类
 */
@Service
public class ProjectInfoServiceImpl extends ServiceImpl<ProjectInfoMapper, ProjectInfo> implements ProjectInfoService {

    @Autowired
    private FeesService feesService;

    @Autowired
    private InvoiceService invoiceService;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private ContactService contactService;

    @Autowired
    private ExecuteTypeService executeTypeService;

    @Autowired
    private ProjectEvalutionService projectEvalutionService;

    @Autowired
    private AccountService accountService;

    @Autowired
    private ProjectInfoMapper projectInfoMapper;

    private final Logger logger = LoggerFactory.getLogger(ProjectInfoServiceImpl.class);


    /**
     * pc 项目列表
     * 传值status:0/null:全部 1:待申请预算 2:待审批预算 3:已审批预算
     * status:   '0：待申请 1：待审批预算 2：预算未通过 3：待报销  4：待审批报销 5：已报销 6：报销未通过'
     * @param req
     * @return
     */
    @Override
    public List<ProjectListInfo> selProjectInfoPc(PageRequest req) {
        List<Integer> statusList = new ArrayList<>();
        Map<String,Object> map =new HashMap<>();
        if(req.getStatus()!=null){
            switch (req.getStatus()){
                case 1:statusList.add(0);statusList.add(2);break;
                case 2:statusList.add(1);break;
                case 3:statusList.add(3);statusList.add(4);statusList.add(5);statusList.add(6);break;
            }
        }
        if (statusList.size()!=0){
            map.put("statusList",statusList);
        }
        //flag   0:顺序 1:倒序
        Integer flag = 0;
        String order = "pi.start_time";
        map.put("order",order);
        map.put("flag",flag);
        map.put("keyword",req.getKeyword());
        List<ProjectInfo> projects = projectInfoMapper.selProjectInfo(map);
        List<ProjectListInfo> projectListInfos=new ArrayList<>();
        for(ProjectInfo p: projects){
            Fees bugFees = feesService.getOne(new QueryWrapper<Fees>().eq("project_id",p.getId()).eq("rei_bug_flag",0));
            Fees reiFees = feesService.getOne(new QueryWrapper<Fees>().eq("project_id",p.getId()).eq("rei_bug_flag",1));
            Customer customer=customerService.getById(p.getCustomerId());
            Contact contact = contactService.getById(p.getContactId());
            ExecuteType executeType = executeTypeService.getById(p.getExcuteTypeId());
            ProjectEvalution projectEvalution = projectEvalutionService.getById(p.getProjectEvalutionId());
            Account account = accountService.getOne(new QueryWrapper<Account>().eq("id",p.getAccountId()));
            Account auxiliary_account = accountService.getOne(new QueryWrapper<Account>().eq("id",p.getAuxiliaryAccountId()));
            List<Invoice> invoices = invoiceService.list(new QueryWrapper<Invoice>().eq("project_id",p.getId()));

            //生成对象   复制项目信息  设置返回对象
            ProjectListInfo projectListInfo = new ProjectListInfo();
            BeanUtils.copyProperties(p, projectListInfo);
            //客户
            if(customer!=null){
                projectListInfo.setCustomer(customer.getName());
            }
            //联系人
            if(contact!=null){
                projectListInfo.setContact(contact.getName());
                projectListInfo.setLinkPhone(contact.getPhone());
            }
            //预算\报销费用
            projectListInfo.setBugFees(bugFees);
            projectListInfo.setReiFees(reiFees);
            //执行方式
            if(executeType != null){
                projectListInfo.setExecuteType(executeType.getExecuteType());
            }
            //评价信息
            if(projectEvalution != null){
                projectListInfo.setScore(projectEvalution.getScore());
                projectListInfo.setMessage(projectEvalution.getMessage());
                projectListInfo.setOther(projectEvalution.getOther());
            }
            //主控督导
            if(account != null){
                projectListInfo.setAccount(account.getName());
            }
            //协同督导
            if (auxiliary_account != null){
                projectListInfo.setAuxiliary_account(auxiliary_account.getName());
            }
            //开票信息
            if (invoices != null && invoices.size()>0){
                projectListInfo.setInvoice(invoices);
            }
            projectListInfos.add(projectListInfo);
        }
        Integer size = projectListInfos.size();
        Integer pageSize = req.getPs()==null?10:req.getPs();
        Integer currentPage = req.getPn()==null?1:req.getPn();
        if (Objects.nonNull(projectListInfos) || projectListInfos.size() > 0) {
            projectListInfos = projectListInfos.subList(pageSize * (currentPage - 1), ((pageSize * currentPage) > size ? size : (pageSize * currentPage)));
        }
        return projectListInfos;
    }

    /**
     * app 项目列表
     * 传值status:0/null:全部 1:待申请预算 2:待审批预算 3:已审批预算
     * status:   '0：待申请 1：待审批预算 2：预算未通过 3：待报销  4：待审批报销 5：已报销 6：报销未通过'
     * orderFlag 排序方式 状态值   0:计划时间顺序 1:计划时间倒序 2:主督导顺序 3:主督导倒序 4:预算毛利率顺序 5:预算毛利率倒序
     * @param req
     * @return
     */
    @Override
    public List<ProjectListInfo> selProjectInfoApp(PageRequest req) {
        Account accountOnline = accountService.findUserInfoByToken();
        List<Integer> statusList = new ArrayList<>();
        Map<String,Object> map =new HashMap<>();
        if(req.getStatus()!=null){
            switch (req.getStatus()){
                case 1:statusList.add(0);statusList.add(2);break;
                case 2:statusList.add(1);break;
                case 3:statusList.add(3);statusList.add(4);statusList.add(5);statusList.add(6);break;
            }
        }
        if (statusList.size()!=0){
            map.put("statusList",statusList);
        }
        //flag   0:顺序 1:倒序
        Integer flag = 0;
        String order = "pi.start_time";
        if (req.getOrderFlag() != null){
            switch (req.getOrderFlag()){
                case 0:order="pi.start_time";flag = 0;break;
                case 1:order="pi.start_time";flag = 1;break;
                case 2:order="pi.account_id";flag = 0;break;
                case 3:order="pi.account_id";flag = 1;break;
                case 4:order="f.rate";flag = 0;break;
                case 5:order="f.rate";flag = 1;break;
            }
        }
        map.put("order",order);
        map.put("flag",flag);
        if (req.getRole().equals(3)){
            map.put("accountId",req.getAccountId());
        }
        List<ProjectInfo> projects = projectInfoMapper.selProjectInfo(map);
        List<ProjectListInfo> projectListInfos=new ArrayList<>();
        for(ProjectInfo p: projects){
            ProjectEvalution projectEvalution = projectEvalutionService.getById(p.getProjectEvalutionId());
            List<Invoice> invoices = invoiceService.list(new QueryWrapper<Invoice>().eq("project_id",p.getId()));

            //生成对象   复制项目信息  设置返回对象
            ProjectListInfo projectListInfo = new ProjectListInfo();
            BeanUtils.copyProperties(p, projectListInfo);

            //0:白色  1:黄色
            ButtenInfo projectDetailBtn=new ButtenInfo(ButtenEnum.PROJECT_DETAIL.getCode(),ButtenEnum.PROJECT_DETAIL.getMsg(),0);
            ButtenInfo budgetApplicationBtn=new ButtenInfo(ButtenEnum.BUDGET_APPLICATION.getCode(),ButtenEnum.BUDGET_APPLICATION.getMsg(),1);
            ButtenInfo reBudgetApplicationBtn=new ButtenInfo(ButtenEnum.REBUDGET_APPLICATION.getCode(),ButtenEnum.REBUDGET_APPLICATION.getMsg(),1);
            ButtenInfo budgetDetailBtn=new ButtenInfo(ButtenEnum.BUDGET_DETAIL.getCode(),ButtenEnum.BUDGET_DETAIL.getMsg(),0);
            ButtenInfo reviewBudgetBtn=new ButtenInfo(ButtenEnum.REVIEW_BUDGET.getCode(),ButtenEnum.REVIEW_BUDGET.getMsg(),1);
            ButtenInfo projectEvalutionBtn=new ButtenInfo(ButtenEnum.PROJECT_EVALUTION.getCode(),ButtenEnum.PROJECT_EVALUTION.getMsg(),0);
            ButtenInfo evalutuionProject=new ButtenInfo(ButtenEnum.EVALUTION_PROJECT.getCode(),ButtenEnum.EVALUTION_PROJECT.getMsg(),1);
            ButtenInfo invoiceBtn=new ButtenInfo(ButtenEnum.INVOICE.getCode(),ButtenEnum.INVOICE.getMsg(),1);
            ButtenInfo fillReimbursementBtn=new ButtenInfo(ButtenEnum.FILL_REIMBURSEMENT.getCode(),ButtenEnum.FILL_REIMBURSEMENT.getMsg(),1);
            ButtenInfo invoiceDetailBtn=new ButtenInfo(ButtenEnum.INVOICE_DETAIL.getCode(),ButtenEnum.INVOICE_DETAIL.getMsg(),0);
            ButtenInfo confirmPaymentBtn=new ButtenInfo(ButtenEnum.CONFIRM_PAYMENT.getCode(),ButtenEnum.CONFIRM_PAYMENT.getMsg(),1);
            ButtenInfo paymentReceivedBtn=new ButtenInfo(ButtenEnum.PAYMENT_RECEIVED.getCode(),ButtenEnum.PAYMENT_RECEIVED.getMsg(),0);
            ButtenInfo approvalReimbursementBtn=new ButtenInfo(ButtenEnum.APPROVAL_REIMBURSEMENT.getCode(),ButtenEnum.APPROVAL_REIMBURSEMENT.getMsg(),1);
            ButtenInfo reimbursementDetailBtn=new ButtenInfo(ButtenEnum.REIMBURSEMENT_DETAIL.getCode(),ButtenEnum.REIMBURSEMENT_DETAIL.getMsg(),0);
            ButtenInfo refillInvoice=new ButtenInfo(ButtenEnum.REFILL_REIMBURSEMENT.getCode(),ButtenEnum.REFILL_REIMBURSEMENT.getMsg(),1);

            //按钮返回
            List<ButtenInfo> btnList = new ArrayList<>();
            btnList.add(projectDetailBtn);
            switch (p.getStatus()){
                case 0:
                    if(accountOnline.getRole().equals(3)){
                        btnList.add(budgetApplicationBtn);
                    }
                    break;
                case 1:
                    btnList.add(budgetDetailBtn);
                    if(accountOnline.getRole().equals(1)){
                        btnList.add(reviewBudgetBtn);
                    }
                    break;
                case 2:
                    if(accountOnline.getRole().equals(3)){
                        btnList.add(reBudgetApplicationBtn);
                    }
                    break;
                case 3:
                    if(accountOnline.getRole().equals(3)){
                        btnList.add(fillReimbursementBtn);
                    }
                    break;
                case 4:
                    btnList.add(reimbursementDetailBtn);
                    btnList.add(approvalReimbursementBtn);
                    break;
                case 5:
                    btnList.add(reimbursementDetailBtn);
                    break;
                case 6:
                    btnList.add(refillInvoice);
                    break;
                default:
                    btnList.add(reBudgetApplicationBtn);
            }

            if (p.getStatus().equals(3) || p.getStatus().equals(4) || p.getStatus().equals(5) || p.getStatus().equals(6)){
                //项目评价
                if (accountOnline.getRole().equals(1)||accountOnline.getRole().equals(0)){
                    if (projectEvalution!=null){
                        btnList.add(projectEvalutionBtn);
                    }else{
                        btnList.add(evalutuionProject);
                    }
                }
                if (p.getStatus().equals(3) || p.getStatus().equals(4) || p.getStatus().equals(5) || p.getStatus().equals(6)){
                    //开票
                    if (invoices.size()==0){
                        btnList.add(invoiceBtn);
                    }else if(invoices.size()>0){
                        //开票详情
                        btnList.add(invoiceDetailBtn);
                        Boolean backFlag = true;
                        for (Invoice invoice : invoices){
                            if(invoice.getPaymentCollectionTime()==null){
                                backFlag=false;break;
                            }
                        }
                        //确认回款或者已回款
                        if(backFlag){
                            btnList.add(paymentReceivedBtn);
                        }else{
                            btnList.add(confirmPaymentBtn);
                        }
                    }
                }
            }
            projectListInfo.setButtenInfos(btnList);
            projectListInfos.add(projectListInfo);
        }
        return projectListInfos;
    }

    @Override
    public ProjectListInfo selProjectDetail(Integer projectId) {
        ProjectInfo projectInfo = projectInfoMapper.selectById(projectId);
        //生成对象   复制项目信息  设置返回对象
        ProjectListInfo projectListInfo = new ProjectListInfo();
        BeanUtils.copyProperties(projectInfo, projectListInfo);
        Customer customer=customerService.getById(projectInfo.getCustomerId());
        Contact contact = contactService.getById(projectInfo.getContactId());
        ExecuteType executeType = executeTypeService.getById(projectInfo.getExcuteTypeId());
        Account account = accountService.getOne(new QueryWrapper<Account>().eq("id",projectInfo.getAccountId()));
        Account auxiliary_account = accountService.getOne(new QueryWrapper<Account>().eq("id",projectInfo.getAuxiliaryAccountId()));
        //客户
        if(customer!=null){
            projectListInfo.setCustomer(customer.getName());
        }
        //联系人
        if(contact!=null){
            projectListInfo.setContact(contact.getName());
            projectListInfo.setLinkPhone(contact.getPhone());
        }
        //执行方式
        if(executeType != null){
            projectListInfo.setExecuteType(executeType.getExecuteType());
        }
        //主控督导
        if(account != null){
            projectListInfo.setAccount(account.getName());
        }
        //协同督导
        if (auxiliary_account != null){
            projectListInfo.setAuxiliary_account(auxiliary_account.getName());
        }
        return projectListInfo;
    }

    public static void main(String[] args) {
    }
}
